package com.hs.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hs.common.api.CommonResult;
import com.hs.common.api.TokenInfo;
import com.hs.user.entity.User;
import com.hs.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 胡尚
 * @since 2024-07-26
 */
@RestController
@RequestMapping("/user")
@Api(tags = "UserController", description = "用户登录")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    @ApiOperation("用户登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Map> login(@RequestParam String username,
                              @RequestParam String password,
                              HttpServletRequest request){

        TokenInfo tokenInfo = userService.login(username, password);


        if (tokenInfo == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }

        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", tokenInfo.getAccess_token());
        tokenMap.put("refreshToken",tokenInfo.getRefresh_token());

        // TODO 用户信息存redis

        return CommonResult.success(tokenMap);

    }


    @ApiOperation("查询用户信息")
    @GetMapping( "/queryUser")
    @ResponseBody
    public CommonResult<User> queryUser(@RequestParam String username, HttpServletRequest request){

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userService.getOne(userQueryWrapper);

        return CommonResult.success(user);

    }


    @RequestMapping("/index")
    public CommonResult<String> resource(){
        log.debug("模拟一个正常接口，请求会携带token，经过gateway，再路由转发到该接口上");
        return CommonResult.success("success  index");
    }



}

